package gl.java.umsp.match;

import gl.java.umsp.event.Event;
import gl.java.umsp.event.EventSubscriber;
import gl.java.umsp.event.IEventSubscriber;
import gl.java.umsp.user.IUserRoomStateChangedListener;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import static gl.java.umsp.event.Event.USER_ENTER_ROOM;
import static gl.java.umsp.event.Event.USER_EXIT_ROOM;
import static gl.java.umsp.event.Event.USER_OFF_LINE;

@Slf4j
public class MatchUserEventDispatcher implements IEventSubscriber {
    private List<IUserRoomStateChangedListener> mIUserRoomStateChangedListener = new CopyOnWriteArrayList<IUserRoomStateChangedListener>();

    public void add(IUserRoomStateChangedListener roomList) {
        mIUserRoomStateChangedListener.add(roomList);
    }


    private MatchUserEventDispatcher() {
        EventSubscriber.registerAsyncSubscriberCallBack(this, Event.USER_ENTER_ROOM, Event.USER_EXIT_ROOM, Event.USER_OFF_LINE);
    }

    public static MatchUserEventDispatcher getInstance() {
        return Single.INSTANCE;
    }

    @Override
    public void onMessage(String channel, String message) {
        try {
            for (IUserRoomStateChangedListener l : mIUserRoomStateChangedListener) {

                JSONObject o = new JSONObject(message);
                final int userID = o.getInt("userID");
                if (channel.equals(USER_ENTER_ROOM)) {
                    String roomID = o.getString("roomID");
                    l.onUserEnter(userID, roomID);
                } else if (channel.equals(USER_EXIT_ROOM)) {
                    String roomID = o.getString("roomID");
                    l.onUserLeave(userID, roomID);
                } else if (channel.equals(USER_OFF_LINE)) {
                    l.onUserDisconnect(userID);
                }
            }
        } catch (Exception e) {
            log.warn(" fail,match user event exception:" + message);
            e.printStackTrace();
        }
    }

    private static class Single {
        public static MatchUserEventDispatcher INSTANCE = new MatchUserEventDispatcher();
    }
}
